package com.dmj.sqldsl.builder.table;

import com.dmj.sqldsl.builder.column.ColumnBuilder;
import com.dmj.sqldsl.builder.column.LambdaColumnBuilder;
import com.dmj.sqldsl.builder.column.type.ColumnLambda;
import com.dmj.sqldsl.builder.column.type.TypeClass;
import com.dmj.sqldsl.builder.config.EntityConfig;
import com.dmj.sqldsl.model.column.Column;
import com.dmj.sqldsl.model.table.SimpleTable;
import com.dmj.sqldsl.model.table.Table;
import java.util.List;
import lombok.EqualsAndHashCode;

@EqualsAndHashCode
public class EntityBuilder implements TableBuilder {

  private final TypeClass entityType;

  public static EntityBuilder alias(Class<?> entityClass) {
    return new EntityBuilder(entityClass,
        String.format("%s_%s", entityClass.hashCode(), new Object().hashCode()));
  }

  private EntityBuilder(Class<?> entityClass, String tableId) {
    this.entityType = new TypeClass(entityClass, tableId);
  }

  public EntityBuilder(Class<?> entityClass) {
    this.entityType = new TypeClass(entityClass);
  }

  public <T, R> ColumnBuilder<T, R> col(ColumnLambda<T, R> lambda) {
    return new LambdaColumnBuilder<>(lambda.getLambdaType(), entityType.getId());
  }

  @Override
  public Table buildTable(EntityConfig config) {
    return new SimpleTable(config.getTableName(entityType.getType()), entityType.getId());
  }

  @Override
  public List<Column> buildColumns(EntityConfig config) {
    return config.getColumns(entityType.getType(), entityType.getId());
  }
}
